package org.langqiao.cross.domain;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.langqiao.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/testCrossDomainController.do")
public class TestCrossDomainController {
	
	@RequestMapping(params = "getUserList")
	@ResponseBody
	public String getUserList(HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		response.setHeader("Access-Control-Allow-Origin","*");
		List<User> list = getUsers();
		JSONObject json = new JSONObject();
		String jsonStr = json.toJSONString(list);
		System.out.println(jsonStr);
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(jsonStr);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out != null){
				out.close();
			}
		}
		return null;
	}
	
	private List<User> getUsers() {
        List<User> users = new ArrayList<User>();
        
        User user1 = new User();
        user1.setUsername("李坏");
        user1.setPassword("LiHuai");
        
        User user2 = new User();
        user2.setUsername("阿飞");
        user2.setPassword("aFei");
        
        User user3 = new User();
        user3.setUsername("陆小凤");
        user3.setPassword("LuXiaoFeng");
        
        users.add(user1);
        users.add(user2);
        users.add(user3);
        
        return users;
    }
}
